import commonJs from '../../utils/common.js';
import tokenManager from '../../mpf/auth/token-manager.js';
Component({
  properties: {
    // 商品详情名称
    name:{
      type: String
    },
    // 当前选中的sku
    sku: {
      type: String
    },
    // 初始input数值
    inputnum:{
      type: Number,
      value: 1
    },
    // 商品规格样式
    normalGoods:{
      type: String,
      observer: function (newData, oldData) {
        this.setData({
          goodsType: newData
        })
      }
    },
    // 所有sku组合
    skuinfo: {
      type: Array,
      observer: function (newData, oldData) {
        this.getSkuInfo(newData)
      }
    },
    // 弹窗开启关闭
    standardType: {
      type: Boolean,
      observer: function (newData, oldData) {
        this.translate()
      }
    },
    btnStandType:{
      type: Number,
      value: 0
    }
  },
  data: {
    goodsType: 0, //0购物车进入 2.普通商品有加入购物车按钮
    img_base_url: global.IMG_BASE_PATH,
    web_base_url: global.WEB_BASE_PATH,
    btnTxt: ['免费领取','立即预约','确认购买'],
    // 组合后的规格
    skuInfo:[],
    // 组合前的规格
    skuList:[],
    // 无库存规格
    noStockList:[],
    attrText: '',
    skuId: '',
    // 可以购买的数量
    canPayStock: 0,
    allChoice: false,
    choiceItem: [],
    // 输入框的值
    inputNum: 1,
    // 初始值
    starInput:1, 
    btnLock: false
  },
  methods: {
    getSkuInfo: function(sku){
      if(sku.length == 0) {
        return
      }
      var state = sku[0].specName.split('@');
      var specData = [];
      var noStockList = [];
      for (var i = 0; i < state.length; i++) {
        specData[i] = {};
        specData[i].attr_name = state[i];
        specData[i].value_list = [];
        sku.forEach((item, index)=>{
          if (item.stock == 0) {
            noStockList.push(item);
          }
          specData[i].value_list.push({
            attr_value: item.skuName.split('@')[i],
            // 判断选中状态
            chosed: this.properties.sku.indexOf(item.skuName.split('@')[i]) != -1 ? 1 : 0,
            // 判断库存不足
            disabled: state.length == 1 && item.stock == 0 ? true : false
          })
        })
      }
      // 规格去重
      for (var k = 0; k < specData.length; k++) {
        specData[k].value_list = commonJs.uniqueArray(specData[k].value_list, 'attr_value');
      }
      this.setData({
        skuInfo: specData,
        skuList: sku,
        noStockList: noStockList
      })
      // 如果有库存不足的规格则检验其他规格状态
      if (noStockList.length > 0) {
        specData.forEach((item, index) => {
          for (var j=0; j<item.value_list.length; j++) {
            if (item.value_list[j].chosed == 1) {
              this.checkStatus(item.value_list[j].attr_value, index, j);
              break
            }
          }
        })
      }
      // 组合文字
      this.choiceTxt()
    },
    // 点击选择规格
    choiceValue: function (e) {
      // 如果选中规格无库存不执行下一步操作
      if (!e.currentTarget.dataset.type && e.currentTarget.dataset.disabled) {
        return
      }
      var index = e.currentTarget.dataset.index;
      var list = e.currentTarget.dataset.list;
      // 当前按钮状态
      var chosedValue = this.data.skuInfo[index].value_list[list].chosed;
      var stateList = this.data.skuInfo[index].value_list;
      //判断当前规格选中
      for (var i = 0; i < stateList.length; i++) {
        if (i == list && chosedValue == 0) {
          stateList[i].chosed = true;
        } else {
          stateList[i].chosed = false;
        }
      }
      var attrList = 'skuInfo[' + index + '].value_list';
      this.setData({
        [attrList]: stateList
      })
      // 判断其他规格是否库存不足(多规格)
      if (this.data.skuInfo.length > 1) {
        this.checkStatus(this.data.skuInfo[index].value_list[list].attr_value, index, list)
      }
      // 组合规格id和文字
      this.choiceTxt()
    },
    // 多规格检验status是否库存不足
    checkStatus: function (statusTxt, statusIndex, statusList) {
      // 所有库存为0的规格
      var noStock = this.data.noStockList;
      // 深复制当前已去重的规格
      var allStateList = JSON.parse(JSON.stringify(this.data.skuInfo));
      // 保存当前选中库存不足的规格
      var siglearr = [];
      noStock.forEach((item, index) => {
        if (item.skuName.indexOf(statusTxt) != -1 && item.stock == 0) {
          for (var i = 0; i < allStateList.length; i++) {
            allStateList[i].value_list.forEach((sku, list) => {
              if (item.skuName.indexOf(sku.attr_value) != -1 && sku.attr_value != statusTxt) {
                siglearr.push(sku)
              }
            })
          }
        }
      })
      // 对比遍历当前所有的库存规格
      allStateList.forEach((attrs, i) => {
        if (i != statusIndex) {
          attrs.value_list.forEach((vals, k) => {
            allStateList[i].value_list[k].disabled = false;
            for (var j = 0; j < siglearr.length; j++) {
              if (!allStateList[i].value_list[k].disabled && siglearr[j].attr_value == vals.attr_value && allStateList[statusIndex].value_list[statusList].chosed == 1) {
                allStateList[i].value_list[k].disabled = true;
              }
            }
          })
        }
      })
      // 重新改变数组
      this.setData({
        skuInfo: allStateList
      })
    },
    // 组合文字
    choiceTxt: function () {
      // sku组合
      var sku = '';
      for (var k = 0; k < this.data.skuInfo.length; k++) {
        for (var j = 0; j < this.data.skuInfo[k].value_list.length; j++) {
          if (this.data.skuInfo[k].value_list[j].chosed == 1) {
            sku = sku + '@' + this.data.skuInfo[k].value_list[j].attr_value;
            break;
          }
        }
      }
      this.setData({
        attrText: sku.slice(1)
      });
      // 检验规格并回调当前规格
      this.checkUp();
    },
    // 检验规格是否全选
    checkUp: function () {
      var skuList = this.data.skuList;
      for (var i = 0; i < skuList.length; i++) {
        if (skuList[i].skuName == this.data.attrText) {
          this.setData({
            inputNum: skuList[i].stock == 0 ? 0 : this.data.starInput,
            choiceItem: skuList[i],
            allChoice: true,
            canPayStock: skuList[i].stock, //保存库存
            starInput: 1 //重置初始值
          })
          break
        } else {
          this.setData({
            allChoice: false
          })
        }
      }
    },
    // input输入数量时监控
    numInput: function (e) {
      var num = e.detail.value;
      if (num > 50 && num < this.data.canPayStock) {
        global.showError('已达到购买上限~');
        num = 50;
      } else if (num > this.data.canPayStock) {
        global.showError('已达到购买上限~');
        num = this.data.canPayStock;
      }
      this.setData({
        inputNum: parseInt(num)
      })
    },
    // 离开键盘时监控
    blurInput: function (e) {
      var num = e.detail.value;
      if (num <= 0) {
        num = 1;
      }
      this.setData({
        inputNum: num
      })
    },
    // 加号数量监控
    addInput: function () {
      var num = parseInt(this.data.inputNum) + 1;
      if (num > this.data.canPayStock) {
        global.showError('已达到购买上限~');
        return
      }
      if (num > 50) {
        global.showError('已达到购买上限~');
        return
      }
      this.setData({
        inputNum: num
      })
    },
    //减号数量监控
    minInput: function () {
      var num = parseInt(this.data.inputNum) - 1;
      if (num <= 0) {
        return
      }
      this.setData({
        inputNum: num
      })
    },
    // 确认选择规格
    goConfirm: function (e) {
      if (!tokenManager.get() || tokenManager.get() == '' || tokenManager.get() == null) {
        global.login()
        return
      }
      if (this.data.allChoice) {
        if (this.data.canPayStock == 0) {
          global.showError('已达到购买上限~');
          return
        }
        if (this.data.btnLock){
          return
        }
        this.setData({
          btnLock: true
        })
        var t = setTimeout(()=>{
          this.setData({
            btnLock: false
          })
        }, 500)
        var postMsg = this.data.choiceItem;
        postMsg.inputNum = this.data.inputNum;
        // 是否加入购物车 1: 加入购物车 2: 确认选中操作
        if(e.currentTarget.dataset.type){
          postMsg.type = 1;
        } else {
          postMsg.type = 2;
        }
        //发射事件
        this.closePop();
        this.triggerEvent('myevent', postMsg);
      } else {
        global.showError('请选择规格哦~');
      }
    },
    //关闭弹窗
    closePop: function(){
      var choiceSku = {
        skuName: this.data.attrText && this.data.attrText != '' ? this.data.attrText : '请选择规格',
        num: this.data.inputNum,
        ruleIndex: 0,
        choiceItem: this.data.choiceItem
      }
      // 关闭时发射当前选择的属性
      this.triggerEvent('popevent', choiceSku)
    },
    // 图片弹窗
    popImg: function (e) {
      var urls = e.currentTarget.dataset.urls;
      var result = urls.map((item) => {
        return this.data.img_base_url + item
      })
      wx.previewImage({
        current: this.data.img_base_url + e.currentTarget.dataset.img, // 当前显示图片的http链接
        urls: result // 需要预览的图片http链接列表
      })
    },
    // 动画
    translate: function () {
      var hHeight = wx.getSystemInfoSync().windowHeight;
      this.animation = wx.createAnimation({
        duration: 250
      })
      if (this.properties.standardType) {
        this.translate1(hHeight)
      } else {
        this.translate2(hHeight)
      }
    },
    translate1: function (h) {
      this.animation.translateY(0).opacity(1).step();
      this.setData({
        animation: this.animation.export()
      })
    },
    translate2: function (h) {
      this.animation.translateY(h).opacity(0).step();
      this.setData({
        animation: this.animation.export()
      })
    }
  }
})